﻿using BCCommon;
using BCCommon.TMS.Driver;
using BCEntity.TMS.Driver.DriverCostReport;
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BCData.TMS.Driver.DriverCostReport
{
    public class DriverCostReportData : IDriverCostReportData
    {
        private readonly IDatabaseContext databaseContext;
        private readonly string QUERY = @"SELECT DriverCostReport,CompanyId,CostType,CostTypeStr,Amount,DriverId,DriverPhone,DriverName,Status,BillAddress,OrderNo,OrderId,VehicleNo,VehicleTypeId,VehicleTypeName,TollStation,CreateTime,ApproveTime,Approver,ApproverId,RefuseToReason,Remark,OilConsumption,OilConsumptionPrice FROM DriverCostReport";

        public DriverCostReportData(IDatabaseContext databaseContext)
        {
            this.databaseContext = databaseContext;
        }


        public async Task<DriverCostReportEntity> CostApproveAsync(DriverCostReportEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("DriverCostReport", new[] { "Status", "RefuseToReason", "Approver", "ApproverId", "ApproveTime" }, new[] { "DriverCostReportId" });
            sql = string.Format("{0} {1} WHERE DriverId=?DriverId;", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?DriverCostReportId", entity.DriverCostReportId, DbType.Int64, size: 20);
            parameters.Add("?Status", entity.Status.ToString(), DbType.AnsiString, size: 21);
            parameters.Add("?RefuseToReason", entity.RefuseToReason, DbType.AnsiString, size: 1000);
            parameters.Add("?Approver", entity.Approver, DbType.AnsiString, size: 1000);
            parameters.Add("?ApproverId", entity.ApproverId, DbType.Int64);
            parameters.Add("?ApproveTime", DateTime.Now, DbType.DateTime);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<DriverCostReportEntity>(sql, parameters, databaseContext.Transaction);
        }

        public async Task<(IEnumerable<DriverCostReportEntity>, int)> GetDriverCostReportAsync(long? companyId, string driverPhone, string vehicleNo, string orderNo, DriverCostReportStatus? status, DriverCostReportType? costType, DateTime? start, DateTime? end, bool? ascending, string sortName, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            if (companyId.HasValue)
            {
                wheres.Add("CompanyId =?CompanyId ");
                parameters.Add("?CompanyId", companyId.Value, DbType.Int64);
            }
            if (!string.IsNullOrWhiteSpace(driverPhone))
            {
                wheres.Add("Phone LIKE CONCAT('%',CONCAT(?Phone,'%'))");
                parameters.Add("?Phone", driverPhone.Trim(), DbType.AnsiString);
            }
            if (!string.IsNullOrWhiteSpace(vehicleNo))
            {
                wheres.Add("VehicleNo LIKE CONCAT('%',CONCAT(?VehicleNo,'%'))");
                parameters.Add("?VehicleNo", vehicleNo.Trim(), DbType.AnsiString);
            }
            if (!string.IsNullOrWhiteSpace(orderNo))
            {
                wheres.Add("OrderNo=?OrderNo");
                parameters.Add("?OrderNo", orderNo.Trim(), DbType.AnsiString);
            }
            if (status.HasValue)
            {
                wheres.Add("Status =?Status");
                parameters.Add("?Status", status.Value, DbType.AnsiString);
            }
            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value.Date, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value.AddDays(1).Date, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value.Date, DbType.DateTime);
                parameters.Add("?End", end.Value.AddDays(1).Date, DbType.DateTime);
            }
            if (costType.HasValue)
            {
                wheres.Add("CostType=?CostType");
                parameters.Add("?CostType", costType.Value.ToString(), DbType.AnsiString);
            }
            string sql = string.Format("{0} {1} ORDER BY {4} {5} LIMIT {2}, {3}; SELECT COUNT(1) FROM DriverCostReport {1};",
                QUERY,
                 wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
                pageSize,
                string.IsNullOrWhiteSpace(sortName) ? "CreateTime" : sortName,
                ascending.HasValue && ascending.Value ? "ASC" : "DESC");

            return await databaseContext.Slave.QueryMultipleAsync<DriverCostReportEntity, int>(sql, parameters);
        }

        public async Task<DriverCostReportEntity> GetDriverCostReportAsync(long driverCostReportId)
        {
            string sql = string.Format(@"{0} WHERE DriverCostReportId=?DriverCostReportId LIMIT 1", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?DriverCostReportId", driverCostReportId, DbType.Int64);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<DriverCostReportEntity>(sql, parameters);
        }

        public async Task<(IEnumerable<DriverCostReportEntity>, int)> GetDriverCostReportsByDriverIdAsync(long driverId, DriverCostReportType? costType, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>()
            {
                "DriverId=?DriverId"
            };
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?DriverId", driverId, DbType.Int64);
            if (costType.HasValue)
            {
                wheres.Add("CostType=?CostType");
                parameters.Add("?CostType", costType.Value.ToString(), DbType.AnsiString);
            }
            string sql = string.Format("{0} {1}  LIMIT {2}, {3}; SELECT COUNT(1) FROM DriverCostReport {1};",
             QUERY,
              wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
             (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
             pageSize);

            return await databaseContext.Slave.QueryMultipleAsync<DriverCostReportEntity, int>(sql, parameters);
        }

        public async Task<DriverCostReportEntity> InserAsync(DriverCostReportEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("DriverCostReport", new string[] { "CompanyId", "CostType", "CostTypeStr", "Amount", "DriverId", "DriverPhone", "DriverName", "Status", "BillAddress", "OrderNo", "OrderId", "VehicleTypeId", "VehicleTypeName", "TollStation", "Remark", "OilConsumption", "OilConsumptionPrice" });
            sql = string.Format("{}  WHERE DriverCostReportId=LAST_INSERT_ID()");
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?CompanyId", entity.CompanyId, DbType.Int32);
            parameters.Add("?CostType", entity.CostType, DbType.AnsiString, size: 20);
            parameters.Add("?CostTypeStr", entity.CostTypeStr, DbType.AnsiString, size: 20);
            parameters.Add("?Amount", entity.Amount, DbType.Decimal);
            parameters.Add("?DriverId", entity.DriverId, DbType.Int64);
            parameters.Add("?DriverPhone", entity.DriverPhone, DbType.AnsiString, size: 20);
            parameters.Add("?DriverName", entity.DriverName, DbType.AnsiString, size: 50);
            parameters.Add("?Status", entity.Status, DbType.AnsiString, size: 20);
            parameters.Add("?BillAddress", entity.BillAddress, DbType.AnsiString);
            parameters.Add("?OrderNo", entity.OrderNo, DbType.AnsiString, size: 50);
            parameters.Add("?OrderId", entity.OrderId, DbType.Int64, size: 50);
            parameters.Add("?VehicleTypeId", entity.VehicleTypeId, DbType.Int64, size: 50);
            parameters.Add("?VehicleTypeName", entity.VehicleTypeName, DbType.AnsiString, size: 20);
            parameters.Add("?TollStation", entity.TollStation, DbType.AnsiString, size: 50);
            parameters.Add("?Remark", entity.Remark, DbType.AnsiString, size: 50);
            parameters.Add("?OilConsumption", entity.OilConsumption, DbType.Decimal);
            parameters.Add("?OilConsumptionPrice", entity.OilConsumptionPrice, DbType.Decimal);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<DriverCostReportEntity>(sql, parameters, databaseContext.Transaction);
        }
    }
}
